# 导入数据表
from app_blog.models import Advertisement
from app_article.models import Category, Tags, Article
from app_user.models import UserInfo
# 导入聚合函数
from django.db.models import Count
# 导入归档辅助函数
from django.db.models.functions import TruncMonth
# 注册自定义标签
from django import template
# 导入分页器
import random

register = template.Library()


@register.inclusion_tag('blog_inclusion_tags/adv_label.html')
def adv_main():
    adv_obj = Advertisement.objects.all().order_by('pk')
    adv_list = random.choices(adv_obj, k=4)
    return locals()


@register.inclusion_tag('blog_inclusion_tags/left_menu_site.html')
def left_menu(request):
    username = request.get_full_path().split("/")[2]
    user_obj = UserInfo.objects.get(username=username)
    # 统计每个分类下的文章
    category_all = Category.objects.filter(blog=user_obj.blog).annotate(article_count=Count('article__pk')).values(
        'pk', 'name', 'article_count')
    # print(category_all)  # <QuerySet [{'category': 'user001分类1', 'article_count': 0},]>

    # 统计每个标签下的文章  # 数字不一定是文章总数，因为标签是多对多
    tags_all = Tags.objects.filter(blog=user_obj.blog).annotate(
        article_count=Count('article__pk')).values('pk', 'name', 'article_count')
    # print(tags_all)  # <QuerySet [{'tag': 'user001标签1', 'article_count': 2},]>
    date_archive = Article.objects.filter(blog=user_obj.blog).annotate(
        year_month=TruncMonth('create_time')).values('year_month').annotate(
        article_count=Count('pk')).order_by('-year_month').values('year_month', 'article_count')
    # print(date_archive)  # <QuerySet [{'month': datetime.datetime(2024, 1, 1, 0, 0), 'article_count': 1},>

    # 统计点赞数排行榜  # 展示前10
    like_rank = Article.objects.filter(blog=user_obj.blog).order_by('-up_count').values('id', 'title', 'up_count')[:10]
    # print(like_rank)  # <QuerySet [{'title': 'Kotlin 协程基础使用学习', 'up_count': 0},>
    return locals()
